﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using CNotebook;
using CNotebook.Inventory;


namespace NotebookS2
{
    public partial class GoodsReceipt : RibbonForm
    {
        public GoodsReceipt()
        {
            InitializeComponent();
        }
        
        public string ConnectionString { get; set; }
        public bool IsMultipleWarehouse { get; set; }
        public string DefaultWarehouse { get; set; }
        public DataTable LineItems { get; set; }
        
        #region Functions
        
        public void PrintPreview()
        {
            PRNT_IGN oPrint = new PRNT_IGN();

            oPrint.ConnectionString = this.ConnectionString;
            oPrint.DocumentNumber = txtDocNum.Text;

            oPrint.WindowState = FormWindowState.Maximized;
            oPrint.ShowDialog();
        }
        
        void InitializeSeries()
        {

            string _RECEIPT_OBJTYPE_VAR = "101";
            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();

            if (oSeries.IsAutoNumber(_RECEIPT_OBJTYPE_VAR) == true)
            {
                txtDocNum.Properties.ReadOnly = true;
                txtDocNum.Text = "##########";

            }
            oSeries.Close();
            
        }

        void DisableControls()
        {

            foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridView1.Columns)
            {

                oColumn.OptionsColumn.AllowEdit = false;

            }


            txtDocNum.Enabled = false;
            txtReference.ReadOnly = true;
            txtRemarks.ReadOnly = true;
            cboTransaction.Enabled = false;
            txtStatus.Enabled = false;
            dtPostDate.Enabled = false;
            cboWarehouse.Enabled = false;
            txtDateCreated.Enabled = false;
            txtCreatedBy.Enabled = false;
            txtDateModified.Enabled = false;
            txtModifiedBy.Enabled = false;

            btnAdd.Enabled = false;


        }

        void EnableControls()
        {

            foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridView1.Columns)
            {
                if (oColumn.Name == "ItemCode" || oColumn.Name == "Qty" || oColumn.Name == "LotNumber" || oColumn.Name == "ExpiryDate")
                {
                    oColumn.OptionsColumn.AllowEdit = true;
                }

            }

            if (this.IsMultipleWarehouse == true)
            {
                cboWarehouse.Enabled = true;
            }

            txtDocNum.Enabled = false;
            txtReference.ReadOnly = false;
            txtRemarks.ReadOnly = false;

            txtStatus.Enabled = false;
            dtPostDate.Enabled = true;
          
            txtDateCreated.Enabled = false;
            txtCreatedBy.Enabled = false;
            txtDateModified.Enabled = false;
            txtModifiedBy.Enabled = false;

            btnAdd.Enabled = false;


        }

        string GetNewSeries()
        {
            string _NEXT_SERIES = "";
            string _RECEIPT_OBJTYPE_VAR = "101";

            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();
            if (oSeries.IsAutoNumber(_RECEIPT_OBJTYPE_VAR) == true)
            {
                _NEXT_SERIES = oSeries.GetNewSeries(_RECEIPT_OBJTYPE_VAR);
            }
            else
            {
                _NEXT_SERIES = txtDocNum.Text;
            }
            oSeries.Close();

            return _NEXT_SERIES;
        }

        #endregion
        
        
        #region Initialize

        DataTable GetLineItem()
        {
            DataTable _table = new DataTable();
            _table.Columns.Add("DocNum", typeof(string));
            _table.Columns.Add("ItemCode", typeof(string));
            _table.Columns.Add("ItemName", typeof(string));
            _table.Columns.Add("UoM", typeof(string));
            _table.Columns.Add("Qty", typeof(int));
            _table.Columns.Add("UnitCost", typeof(string));
            _table.Columns.Add("LotNumber", typeof(string));
            _table.Columns.Add("ExpiryDate", typeof(DateTime));
            _table.Columns.Add("MfrDate", typeof(DateTime));

            return _table;
        }

        void RemoveBlankLastRowFirst()
        {
            int iCount = -1;
            gridView1.MoveLast();

            int[] oRow = gridView1.GetSelectedRows();

            iCount = oRow[0];
            string sItemCode = "";


            sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();

            if (sItemCode.Trim() == "")
            {
                gridView1.DeleteRow(iCount);
            }


        }

        void BindLotNumber(string _itemcode)
        {
            StockManager oManager = new StockManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            DataTable _table = oManager.GetLotNumbers(_itemcode);

            oManager.Close();

            foreach (DataRow oRow in _table.Rows)
            {
                cboLotNumber.Items.Add(oRow["LotNumber"].ToString());
            }
        }

        void BindWarehouse()
        {
            WarehouseManager oManager = new WarehouseManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();
            DataTable oTable = new DataTable();

            oTable = oManager.GetWarehouse();


            cboWarehouse.Visible = false;
            cboWarehouse.Properties.DataSource = oTable;
            cboWarehouse.Properties.DisplayMember = "Dscription";
            cboWarehouse.Properties.ValueMember = "Code";


            cboWarehouse.Properties.Columns.Clear();
            DevExpress.XtraEditors.Controls.LookUpColumnInfo col;

            col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Code", "Code", 100);

            col.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;


            cboWarehouse.Properties.Columns.Add(col);

            col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Dscription", "Dscription", 100);

            cboWarehouse.Properties.Columns.Add(col);

            cboWarehouse.Visible = true;


            oManager.Close();



        }

        void BindTransaction()
        {
            ReceiptManager oManager = new ReceiptManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();
            DataTable _table = oManager.GetTransaction();
            oManager.Close();

            cboTransaction.Properties.DisplayMember = "TransactionName";
            cboTransaction.Properties.ValueMember = "TransactionName";
            cboTransaction.Properties.DataSource = _table;

            cboTransaction.Properties.Columns.Clear();
            DevExpress.XtraEditors.Controls.LookUpColumnInfo col;

            col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("TransactionName", "TransactionName", 100);

            col.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;


            cboWarehouse.Properties.Columns.Add(col);

            cboTransaction.Refresh();
        }

        public int ObjectType { get { return 101; } }
        
        public string ActiveUserID { get; set; }

        string ApplyAuthorization()
        {
            UserManager oManager = new UserManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            string iAccessType = oManager.GetAccessType(this.ObjectType, this.ActiveUserID);

            oManager.Close();

            switch (iAccessType)
            {
                case "Full Access":
                    FullAccess();
                    break;
                case "Read Only":
                    ApplyReadOnly();
                    break;
                case "No Access":
                    NoAccess();
                    break;
            }

            return iAccessType;
        }

        int ApplyReadOnly()
        {
            DisableControls();

            txtStatus.Properties.Buttons[0].Enabled = false;
            txtStatus.Properties.Buttons[1].Enabled = false;

            
            return 2;
        }

        int FullAccess()
        {
            txtStatus.Properties.Buttons[0].Enabled = true;
            txtStatus.Properties.Buttons[1].Enabled = true;
            
            return 1;
        }

        int NoAccess()
        {
            MessageBox.Show("You have no right to access this module!!!!", "Security Policy", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            return 3;

        }

        #endregion

        private void GoodsReceipt_Load(object sender, EventArgs e)
        {
            
            this.LineItems = GetLineItem();
            BindTransaction();
            gridControl1.DataSource = this.LineItems;
            gridControl1.Refresh();

            DateTime _Now = System.DateTime.Now;

            txtModifiedBy.Text = this.ActiveUserID;
            txtDateCreated.Text = _Now.ToString();
            txtCreatedBy.Text = this.ActiveUserID;
            txtDateModified.Text = _Now.ToString();
            dtPostDate.EditValue = _Now;
            
            if (gridView1.DataRowCount <= 0)
            {
                gridView1.AddNewRow();
            }

            BindWarehouse();
            cboWarehouse.EditValue = this.DefaultWarehouse;
            if (this.IsMultipleWarehouse == false)
            {
                cboWarehouse.Enabled = false;
            }

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (btnAdd.Text == "Add")
            {
                if (gridView1.RowCount > 0)
                {
                    if (cboWarehouse.EditValue != null)
                    {
                        RemoveBlankLastRowFirst();
                        ReceiptUnit oUnit = new ReceiptUnit();
                        txtDocNum.Text = GetNewSeries();
                        oUnit.DocNumber = txtDocNum.Text;
                        oUnit.Reference = txtReference.Text;
                        oUnit.Transaction = cboTransaction.Text;
                        oUnit.Remarks = txtRemarks.Text;
                        oUnit.WarehouseCode = cboWarehouse.EditValue.ToString();
                        oUnit.WarehouseName = cboWarehouse.Text.ToString();
                        oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                        oUnit.DocumentStatus = txtStatus.Text;

                        oUnit.DateCreated = Convert.ToDateTime(txtDateCreated.Text);
                        oUnit.CreatedBy = this.ActiveUserID;
                        oUnit.DateModified = Convert.ToDateTime(txtDateModified.Text);
                        oUnit.ModifiedBy = this.ActiveUserID;

                        oUnit.LineItems = this.LineItems;


                        ReceiptManager oManager = new ReceiptManager();
                        oManager.ConnectionString = this.ConnectionString;
                        oManager.Open();
                        System.Data.SqlClient.SqlException ex = oManager.AddReceipt(oUnit);
                        oManager.Close();

                        if (ex == null)
                        {
                            MessageBox.Show("Document successfully saved!!!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            btnAdd.Text = "Update";
                        }
                        else
                        {
                            MessageBox.Show(ex.Message.ToString(), "Notebook Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                          
                    }
                    else
                    {
                        MessageBox.Show("Please select warehouse!!!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    MessageBox.Show("Please add line items!!!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                if (gridView1.RowCount > 0)
                {
                    if (cboWarehouse.EditValue != null)
                    {
                        RemoveBlankLastRowFirst();
                        ReceiptUnit oUnit = new ReceiptUnit();
                            
                        oUnit.DocNumber = txtDocNum.Text;
                        oUnit.Reference = txtReference.Text;
                        oUnit.Transaction = cboTransaction.Text;
                        oUnit.Remarks = txtRemarks.Text;
                        oUnit.WarehouseCode = cboWarehouse.EditValue.ToString();
                        oUnit.WarehouseName = cboWarehouse.Text.ToString();
                        oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                        oUnit.DocumentStatus = txtStatus.Text;

                        oUnit.DateCreated = Convert.ToDateTime(txtDateCreated.Text);
                        oUnit.CreatedBy = this.ActiveUserID;
                        oUnit.DateModified = Convert.ToDateTime(txtDateModified.Text);
                        oUnit.ModifiedBy = this.ActiveUserID;

                        oUnit.LineItems = this.LineItems;


                        ReceiptManager oManager = new ReceiptManager();
                        oManager.ConnectionString = this.ConnectionString;
                        oManager.Open();
                        System.Data.SqlClient.SqlException ex = oManager.UpdateReceipt(oUnit);
                        oManager.Close();

                        if (ex == null)
                        {
                            MessageBox.Show("Document successfully saved!!!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            MessageBox.Show(ex.Message.ToString(), "Notebook Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                          
                    }
                    else
                    {
                        MessageBox.Show("Please select warehouse!!!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    MessageBox.Show("Please add line items!!!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            
        }

        private void txtItemCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_ITEM oFindItemForm = new FND_ITEM();
            oFindItemForm.ConnectionString = this.ConnectionString;
            oFindItemForm.ShowDialog();

            string sItemCode = oFindItemForm.SelectedItemCode;

            if (sItemCode != null)
            {
                ItemManager oManager = new ItemManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                DataTable oTable = oManager.GetItemMasterData(sItemCode);
                oManager.Close();

                int iRowIndex = gridView1.FocusedRowHandle;

                if (iRowIndex < 0)
                {
                    iRowIndex = 0;
                }
                int iCount = gridView1.FocusedRowHandle;
                gridView1.SetRowCellValue(iCount, gridView1.Columns["LineNum"], iRowIndex);
                gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemCode"], oTable.Rows[0]["ItemCode"].ToString());
                gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemName"], oTable.Rows[0]["Description"].ToString());
                gridView1.SetRowCellValue(iCount, gridView1.Columns["UoM"], oTable.Rows[0]["InvtyUntMsr"].ToString());
                gridView1.SetRowCellValue(iCount, gridView1.Columns["UnitCost"], 0);
                gridView1.SetRowCellValue(iCount, gridView1.Columns["LotNumber"], "N/A");
                gridView1.SetRowCellValue(iCount, gridView1.Columns["ExpiryDate"], System.DateTime.Now);
                gridView1.SetRowCellValue(iCount, gridView1.Columns["MfrDate"], System.DateTime.Now);

                BindLotNumber(sItemCode);
  
            }
        }

        private void gridControl1_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                int iCount = -1;
                int[] oRow = gridView1.GetSelectedRows();

                iCount = oRow[0];
                if (e.KeyCode == Keys.Down)
                {
                    if (gridView1.IsLastRow)
                    {
                        string sItemCode = "";
                        oRow = gridView1.GetSelectedRows();

                        iCount = oRow[0];
                        sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();

                        if (sItemCode != "")
                        {
                            gridView1.AddNewRow();
                        }
                    }
                }

             
            }
            catch
            {
            }
        }

        private void txtItemCode_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    DevExpress.XtraEditors.ButtonEdit oButtonEdit = (DevExpress.XtraEditors.ButtonEdit)sender;

                    string sItemCode = oButtonEdit.Text;
                    ItemManager oManager = new ItemManager();

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    DataTable dt = oManager.GetItemMasterData(sItemCode);

                    oManager.Close();

                    if (dt.Rows.Count > 0)
                    {
                        #region If Has Rows
                        var items = from row in dt.AsEnumerable()
                                    select new
                                    {
                                        ItemCode = row["ItemCode"].ToString(),
                                        Dscription = row["Description"].ToString(),
                                        UoM = row["InvtyUntMsr"].ToString()

                                    };


                        int iCount = -1;
                        int[] oRow = gridView1.GetSelectedRows();

                        iCount = oRow[0];
                        int iRowIndex = gridView1.FocusedRowHandle;

                        if (iRowIndex < 0)
                        {
                            iRowIndex = 0;
                        }
                        foreach (var oUnit in items)
                        {
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["LineNum"], iRowIndex);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemCode"], oUnit.ItemCode);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemName"], oUnit.Dscription);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["UoM"], oUnit.UoM);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["LotNumber"], "N/A");
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["UnitCost"], 0);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["ExpiryDate"], System.DateTime.Now);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["MfrDate"], System.DateTime.Now);

                            BindLotNumber(oUnit.ItemCode);
                        }
                        #endregion



                        gridView1.FocusedColumn = gridView1.Columns["Qty"];
                        gridView1.ShowEditor();

                    }
                    else
                    {
                        DevExpress.XtraEditors.TextEdit oTextBox = (DevExpress.XtraEditors.TextEdit)sender;

                        if (oTextBox.Text != "")
                        {
                            MessageBox.Show("No item found in the Master File!!!", "Item Code", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            oButtonEdit.Focus();
                        }
                    }
                }

                if (e.KeyCode == Keys.Tab)
                {
                    DevExpress.XtraEditors.ButtonEdit oButtonEdit = (DevExpress.XtraEditors.ButtonEdit)sender;

                    string sItemCode = oButtonEdit.Text;
                    ItemManager oManager = new ItemManager();

                    oManager.ConnectionString = this.ConnectionString;
                    oManager.Open();

                    DataTable dt = oManager.GetItemMasterData(sItemCode);

                    oManager.Close();

                    if (dt.Rows.Count > 0)
                    {
                        #region If Has Rows
                        var items = from row in dt.AsEnumerable()
                                    select new
                                    {
                                        ItemCode = row["ItemCode"].ToString(),
                                        Dscription = row["Description"].ToString(),
                                        UoM = row["InvtyUntMsr"].ToString()

                                    };


                        int iCount = -1;
                        int[] oRow = gridView1.GetSelectedRows();

                        iCount = oRow[0];
                        int iRowIndex = gridView1.FocusedRowHandle;

                        if (iRowIndex < 0)
                        {
                            iRowIndex = 0;
                        }
                        foreach (var oUnit in items)
                        {
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["LineNum"], iRowIndex);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemCode"], oUnit.ItemCode);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemName"], oUnit.Dscription);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["UoM"], oUnit.UoM);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["LotNumber"], "N/A");
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["UnitCost"], 0);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["ExpiryDate"], System.DateTime.Now);
                            gridView1.SetRowCellValue(iCount, gridView1.Columns["MfrDate"], System.DateTime.Now);

                            BindLotNumber(oUnit.ItemCode);
                        }
                        #endregion



                        gridView1.FocusedColumn = gridView1.Columns["Qty"];
                        gridView1.ShowEditor();

                    }
                    else
                    {
                        DevExpress.XtraEditors.TextEdit oTextBox = (DevExpress.XtraEditors.TextEdit)sender;

                        if (oTextBox.Text != "")
                        {
                            MessageBox.Show("No item found in the Master File!!!", "Item Code", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            oButtonEdit.Focus();
                        }
                    }
                }
            }
            catch
            {
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtStatus_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Draft")
            {
                txtStatus.Properties.Buttons[0].Visible = true;
                txtStatus.Properties.Buttons[1].Visible = true;
                EnableControls();
              
            }
            if (txtStatus.Text == "Canceled")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = false;
                DisableControls();
            }

            if (txtStatus.Text == "Posted")
            {
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = false;
                DisableControls();
            }

        }

        private void txtStatus_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            ReceiptManager oManager = new ReceiptManager();
            oManager.ConnectionString = this.ConnectionString;
            if (txtStatus.Text == "Draft")
            {
                if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.OK)
                {
                    if (MessageBox.Show("Are you sure you want to post this Document?", "Post Document", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        oManager.Open();
                        oManager.PostReceipt(cboWarehouse.EditValue.ToString(), txtDocNum.Text);
                        oManager.Close();

                        txtStatus.Text = "Posted";


                        ReceiptUnit oUnit = new ReceiptUnit();
                        
                        oUnit.DocNumber = txtDocNum.Text;
                        oUnit.Reference = txtReference.Text;
                        oUnit.Transaction = cboTransaction.Text;
                        oUnit.Remarks = txtRemarks.Text;
                        oUnit.WarehouseCode = cboWarehouse.EditValue.ToString();
                        oUnit.WarehouseName = cboWarehouse.Text.ToString();
                        oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                        oUnit.DocumentStatus = txtStatus.Text;

                        oUnit.DateCreated = Convert.ToDateTime(txtDateCreated.Text);
                        oUnit.CreatedBy = this.ActiveUserID;
                        oUnit.DateModified = Convert.ToDateTime(txtDateModified.Text);
                        oUnit.ModifiedBy = this.ActiveUserID;

                        oUnit.LineItems = this.LineItems;

                        oManager = new ReceiptManager();
                        
                        oManager.ConnectionString = this.ConnectionString;
                        oManager.Open();
                        oManager.UpdateReceipt(oUnit);
                        oManager.Close();


                    }
                }

                if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
                {
                    if (MessageBox.Show("Are you sure you want to cancel this Document?", "Post Document", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        oManager.Open();
                        oManager.CancelReceipt(txtDocNum.Text);
                        oManager.Close();

                        txtStatus.Text = "Canceled";


                        ReceiptUnit oUnit = new ReceiptUnit();

                        oUnit.DocNumber = txtDocNum.Text;
                        oUnit.Reference = txtReference.Text;
                        oUnit.Transaction = cboTransaction.Text;
                        oUnit.Remarks = txtRemarks.Text;
                        oUnit.WarehouseCode = cboWarehouse.EditValue.ToString();
                        oUnit.WarehouseName = cboWarehouse.Text.ToString();
                        oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                        oUnit.DocumentStatus = txtStatus.Text;

                        oUnit.DateCreated = Convert.ToDateTime(txtDateCreated.Text);
                        oUnit.CreatedBy = this.ActiveUserID;
                        oUnit.DateModified = Convert.ToDateTime(txtDateModified.Text);
                        oUnit.ModifiedBy = this.ActiveUserID;

                        oUnit.LineItems = this.LineItems;

                        oManager = new ReceiptManager();

                        oManager.ConnectionString = this.ConnectionString;
                        oManager.Open();
                        oManager.UpdateReceipt(oUnit);
                        oManager.Close();

                    }
                }
            }
        }

        public void ShowSearch()
        {
            try
            {
                FND_RCPT oForm = new FND_RCPT();

                oForm.ConnectionString = this.ConnectionString;
                oForm.ShowDialog();

                string sDocumentNumber = oForm.DocumentNumber;

                ReceiptManager oManager = new ReceiptManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();

                DataTable _table = oManager.GetReceiptDocument(sDocumentNumber);

                DataRow oRow = _table.Rows[0];

                txtDocNum.Text = oRow["DocNum"].ToString();
                txtReference.Text = oRow["Reference"].ToString();
                txtRemarks.Text = oRow["Remarks"].ToString();

                cboTransaction.EditValue = oRow["Trans"].ToString();
                txtStatus.Text = oRow["DocStatus"].ToString();
                dtPostDate.EditValue = Convert.ToDateTime(oRow["PostingDate"]);
                cboWarehouse.EditValue = oRow["WhsCode"].ToString();
                txtDateCreated.Text = oRow["DateCreated"].ToString();
                txtCreatedBy.Text = oRow["CreatedBy"].ToString();
                txtDateModified.Text = oRow["DateModified"].ToString();
                txtModifiedBy.Text = oRow["ModifiedBy"].ToString();

                this.LineItems = oManager.GetReceiptLineItems(sDocumentNumber);

                gridControl1.DataSource = this.LineItems;
                gridControl1.Refresh();
                btnAdd.Text = "Update";


                if (txtStatus.Text == "Draft")
                {
                    if (this.LineItems.Rows.Count == 0)
                    {
                        gridView1.AddNewRow();
                    }
                }
                oManager.Close();

            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        private void GoodsReceipt_Shown(object sender, EventArgs e)
        {
            gridControl1.Select();
            gridView1.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
            gridView1.FocusedColumn = gridView1.Columns["ItemCode"];
            gridView1.ShowEditor();


            txtReference.Focus();

            string _USR_AUTHORIZATION = ApplyAuthorization();
            if (_USR_AUTHORIZATION == "No Access")
            {
                btnCancel_Click(sender, e);
            }
        }

        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down)
            {
                if (gridView1.IsLastRow)
                {
                    string sItemCode = "";
                    

                    int iFocusedRowHandle = gridView1.FocusedRowHandle;
                    sItemCode = gridView1.GetRowCellValue(iFocusedRowHandle, gridView1.Columns["ItemCode"]).ToString();

                    if (sItemCode != "")
                    {
                        gridView1.AddNewRow();

                        gridView1.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
                        gridView1.FocusedColumn = gridView1.Columns["ItemCode"];
                        gridView1.ShowEditor();
                    }
                }
            }

            if (e.KeyCode == Keys.Delete)
            {
                if (btnAdd.Enabled == true)
                {
                    if (MessageBox.Show("Are you sure you want to delete this Row?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {

                        if (gridView1.IsLastRow)
                        {
                            string sItemCode = "";

                            int iFocusedRowHandle = gridView1.FocusedRowHandle;

                            sItemCode = gridView1.GetRowCellValue(iFocusedRowHandle, gridView1.Columns["ItemCode"]).ToString();


                            if (sItemCode != "")
                            {
                                gridView1.DeleteRow(iFocusedRowHandle);
                                gridView1.AddNewRow();
                            }


                            gridView1.RefreshData();

                        }
                        else
                        {

                            string sItemCode = "";

                            int iFocusedRowHandle = gridView1.FocusedRowHandle;

                            sItemCode = gridView1.GetRowCellValue(iFocusedRowHandle, gridView1.Columns["ItemCode"]).ToString();

                            if (sItemCode != "")
                            {
                                gridView1.DeleteRow(iFocusedRowHandle);
                            }

                            gridView1.RefreshData();
                        }
                    }
                }
            }

        }

        private void txtQty_EditValueChanged(object sender, EventArgs e)
        {
            DevExpress.XtraEditors.TextEdit textQty = (DevExpress.XtraEditors.TextEdit)sender;
            double iQty = 0;
            try
            {
                iQty = Convert.ToDouble(textQty.Text);
            }
            catch
            {
                iQty = 0;
            }
            gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Qty"], iQty);
        }

        private void lblModBy_Click(object sender, EventArgs e)
        {

        }

        private void lblDateModified_Click(object sender, EventArgs e)
        {

        }

        private void lblCreatedBy_Click(object sender, EventArgs e)
        {

        }

        private void lblDateCreated_Click(object sender, EventArgs e)
        {

        }

        private void lblWarehouse_Click(object sender, EventArgs e)
        {

        }

        private void lblPostingDate_Click(object sender, EventArgs e)
        {

        }

        private void lblStatus_Click(object sender, EventArgs e)
        {

        }

        private void lblReference_Click(object sender, EventArgs e)
        {

        }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {

        }

        private void GoodsReceipt_Resize(object sender, EventArgs e)
        {
            if (this.Width > 732)
            {
                //lblStatus.Left = this.Width - 247;
                //lblPostingDate.Left = this.Width - 247;
                //lblDateCreated.Left = this.Width - 247;
                //lblCreatedBy.Left = this.Width - 247;
                //lblDateModified.Left = this.Width - 247;
                //lblModBy.Left = this.Width - 247;


                lblStatus.Left = this.Width - 254;
                lblPostingDate.Left = this.Width - 254;
                lblDateCreated.Left = this.Width - 254;
                lblCreatedBy.Left = this.Width - 254;
                lblDateModified.Left = this.Width - 254;
                lblModBy.Left = this.Width - 254;




                txtStatus.Left = this.Width - 175;
                dtPostDate.Left = this.Width - 175;
                txtDateCreated.Left = this.Width - 175;
                txtCreatedBy.Left = this.Width - 175;
                txtModifiedBy.Left = this.Width - 175;
                txtDateModified.Left = this.Width - 175;

                gridControl1.Width = this.Width - 34;
            }
            else
            {
                lblStatus.Left = 478;
                lblPostingDate.Left = 478;
                
                lblDateCreated.Left = 478;
                lblCreatedBy.Left = 478;
                lblDateModified.Left = 478;
                lblModBy.Left = 478;


                txtStatus.Left = 557;
                dtPostDate.Left = 557;
                
                txtDateCreated.Left = 557;
                txtCreatedBy.Left = 557;
                txtModifiedBy.Left = 557;
                txtDateModified.Left = 557;

                gridControl1.Width = 698;
            }


            if (this.Height > 492)
            {
                gridControl1.Height = this.Height - 237;

                Point locationAdd = new Point(5, this.Height - 68);
                Point locationCancel = new Point(86, this.Height - 68);
                btnAdd.Location =  locationAdd;
                btnCancel.Location =  locationCancel;
            }
            else
            {
                gridControl1.Height = 255;

                Point locationAdd = new Point(5, 424);
                Point locationCancel = new Point(86, 424);
                
                btnAdd.Location = locationAdd;
                btnCancel.Location = locationCancel;
            }
        }

        private void xtraScrollableControl1_Click(object sender, EventArgs e)
        {

        }
    }
}
